import { useState, useEffect } from 'react'
import { NavLink } from 'react-router-dom'

import {
  Card,
  Breadcrumb,
  Button,
  Form,
  Input,
  Space,
  Select,
  Table,
  Image,
  Switch,
  Pagination,
  message,
  Drawer,
  Carousel
} from 'antd'
import { GoodsList, GoodsQuery } from '@/types/goods'
import { getGoodsList, getCategories, setState } from '@/api/goods'
import { useFormatPrice } from '@/hooks/format'

const { Option } = Select
const formatPrice = useFormatPrice()

export default function Goods () {
  const [form] = Form.useForm()
  const [goodsQuery, setGoodsQuery] = useState({
    page: 1,
    pageSize: 10,
    proname: '',
    brand: '',
    cateGory: ''
  } as GoodsQuery)
  const [goodsList, setGoodsList] = useState([] as GoodsList[])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  const [cateGories, setCateGories] = useState([] as string[])

  const [open, setOpen] = useState(false)
  const [goods, setGoods] = useState({} as GoodsList)

  const getGoodsListData = async () => {
    try {
      const results = await form.getFieldsValue([
        'proname',
        'category',
        'brand'
      ])
      results.page = page
      results.pageSize = pageSize
      const res = await getGoodsList(results)
      console.log(res)
      setTotal(res.data.total)
      setGoodsList(res.data.items)
    } catch (error) {
      console.log('---error---', error)
    }
  }

  const getCategoriesData = async () => {
    try {
      const res = await getCategories()
      setCateGories(res.data)
    } catch (error) {
      console.log(error)
    }
  }

  const changeState = async (
    type: 'issale' | 'isseckill' | 'isrecommend',
    proid: string,
    state: 0 | 1
  ) => {
    await setState({ type, proid, state })
    if (type === 'issale') {
      message.success('更改是否售卖状态成功')
    } else if (type === 'isseckill') {
      message.success('更改是否秒杀状态成功')
    } else if (type === 'isrecommend') {
      message.success('更改是否推荐状态成功')
    }
  }

  const reset = () => {
    form.resetFields()
    setGoodsQuery({ ...goodsQuery, page: 1, pageSize: 10 })
    getGoodsListData()
  }

  useEffect(() => {
    getGoodsListData()
    getCategoriesData()
  }, [])

  useEffect(() => {
    getGoodsListData()
  }, [page, pageSize])

  const columns = [
    {
      title: '图片',
      dataIndex: 'img2',
      render: (img2: string) => {
        return <Image src={img2} style={{ width: 50, height: 50 }}></Image>
      }
    },
    {
      title: '名称',
      dataIndex: 'proname'
    },
    {
      title: '品牌',
      dataIndex: 'brand'
    },
    {
      title: '分类',
      width: 100,
      dataIndex: 'category',
      filters: Array.from(new Set(goodsList.map(item => item.category))).map(
        item => ({
          text: item,
          value: item
        })
      ),
      onFilter: (value: any, record: any) => record.category.includes(value)
    },
    {
      title: '原价',
      dataIndex: 'originprice'
    },
    {
      title: '折扣',
      dataIndex: 'discount'
    },
    {
      title: '销量',
      dataIndex: 'sales'
    },
    {
      title: '是否秒杀',
      dataIndex: 'issale',
      render: (_: any, record: GoodsList) => {
        return (
          <Switch
            defaultChecked={record.issale === 1}
            onChange={checked => {
              changeState('issale', record.proid, checked ? 1 : 0)
            }}
          />
        )
      }
    },
    {
      title: '是否秒杀',
      dataIndex: 'isseckill',
      render: (_: any, record: GoodsList) => {
        return (
          <Switch
            defaultChecked={record.isseckill === 1}
            onChange={checked => {
              changeState('isseckill', record.proid, checked ? 1 : 0)
            }}
          />
        )
      }
    },
    {
      title: '是否推荐',
      dataIndex: 'isrecommend',
      render: (_: any, record: GoodsList) => {
        return (
          <Switch
            defaultChecked={record.isrecommend === 1}
            onChange={checked => {
              changeState('isrecommend', record.proid, checked ? 1 : 0)
            }}
          />
        )
      }
    },
    {
      title: '操作',
      render: (_: any, record: GoodsList) => {
        return (
          <Button type='primary' onClick={() => showDetail(record)}>
            查看详情
          </Button>
        )
      }
    }
  ]

  const showDetail = (goods: GoodsList) => {
    setOpen(true)
    setGoods(goods)
  }

  return (
    <div>
      <Card>
        <Breadcrumb
          items={[
            {
              title: <NavLink to='/'>首页</NavLink>
            },
            {
              title: '商品管理'
            },
            {
              title: '商品列表'
            }
          ]}
        />
        <Form
          layout={'inline'}
          form={form}
          style={{ marginTop: 20 }}
          size='large'
        >
          <Form.Item label='商品名称' name='proname'>
            <Input
              placeholder='请输入商品名称进行搜索'
              value={goodsQuery.proname}
              onChange={e => {
                setGoodsQuery({ ...goodsQuery, proname: e.target.value })
              }}
            />
          </Form.Item>
          <Form.Item label='商品分类' name='category'>
            <Select style={{ width: 200 }} allowClear>
              {cateGories.map(item => {
                return (
                  <Option key={item} value={item}>
                    {item}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
          <Form.Item label='品牌' name='brand'>
            <Input
              placeholder='请输入品牌进行搜索'
              value={goodsQuery.brand}
              onChange={e => {
                setGoodsQuery({ ...goodsQuery, brand: e.target.value })
              }}
            />
          </Form.Item>
          <Form.Item>
            <Space />
            <Button type='default' style={{ marginRight: 20 }} onClick={reset}>
              清空
            </Button>
            <Button
              type='primary'
              style={{ marginRight: 20 }}
              onClick={getGoodsListData}
            >
              搜索
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card style={{ marginTop: 10 }}>
        <Table
          columns={columns}
          dataSource={goodsList}
          rowKey='proid'
          pagination={false}
        />
        <Pagination
          style={{ marginTop: 20, textAlign: 'center' }}
          current={page}
          pageSize={pageSize}
          total={total}
          pageSizeOptions={[6, 10, 20]}
          showSizeChanger
          showQuickJumper
          showTotal={total => `共 ${total} 页`}
          onChange={(page, pageSize) => {
            setPage(page), setPageSize(pageSize)
          }}
        />
      </Card>
      <Drawer
        title='商品详情'
        placement='right'
        onClose={() => setOpen(false)}
        open={open}
        width={'80%'}
      >
        {/* 轮播图 */}
        <Carousel autoplay>
          {goods.banners &&
            goods.banners[0].split(',').map(item => {
              return (
                <div key={item} style={{ width: 600 }}>
                  <img src={item} />
                </div>
              )
            })}
        </Carousel>
        <h3>{goods.proname}</h3>
        <h4>品牌：{goods.brand}</h4>
        <h4>分类：{goods.category}</h4>
        <h4>
          价格：
          <span style={{ color: 'red' }}>
            ￥{formatPrice(goods.originprice || 0)}
          </span>
        </h4>
        <h4>销量：{goods.sales}</h4>
        <h4>是否售卖：{goods.issale === 1 ? '是' : '否'}</h4>
        <h4>是否秒杀：{goods.isseckill === 1 ? '是' : '否'}</h4>
        <h4>是否推荐：{goods.isrecommend === 1 ? '是' : '否'}</h4>
        <h4>{goods.desc}</h4>
        <h4>图文详情：</h4>
        <div style={{ textAlign: 'center' }}>
          <Image src={goods.img1} />
        </div>
        <div style={{ textAlign: 'center' }}>
          <Image src={goods.img2} />
        </div>
        <div style={{ textAlign: 'center' }}>
          <Image src={goods.img3} />
        </div>
        <div style={{ textAlign: 'center' }}>
          <Image src={goods.img4} />
        </div>
      </Drawer>
    </div>
  )
}
